<?php
namespace app\api\controller\service;

use addons\shopro\model\ActivityGoodsSkuPrice;
use app\admin\validate\shopro\GoodsSkuPrice;
use app\common\controller\Api;
use think\Db;
use think\Loader;
use think\Exception;
/**
 * 首页接口
 */
class Goods extends Api
{
    protected $noNeedLogin = ['categoryGoods','getList','goodsInfo'];
    protected $noNeedRight = ['*'];

    /**
     * 搜索查询项目
     * @return void
     */
    public function getList()
    {
        $uid = $this->auth->isLogin()?$this->auth->id:'';
        $get = input('get.','','trim,strip_tags');
        $get['limit'] = 10;
        $get['page'] = input('page/d',1);
        if(array_key_exists('name',$get) && $uid)
        {
            \app\api\model\service\SearchLog::create(['user_id'=>$uid,'name'=>$get['name']]);
        }
        $list = \app\api\model\service\Goods::searchGoods($get);
        if($list)
        {
            foreach ($list as &$value)
            {
                $value['shopname'] = $value['shop_id']?\app\api\model\service\Shop::getName($value['shop_id']):'';;
            }
        }
        $this->success('信息返回成功',$list);
    }


    public function goodsAddList()
    {
        $id = input('id/d','');
        $list = \app\api\model\service\GoodsAdd::where(['goods_id'=>$id,'state'=>1])->field('id,name,price,cost_seconds')->select();
        $this->success('信息返回成功',$list);
    }


    /**
     * 首页分类项目列表
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function categoryGoods()
    {
        $city = input('city','');
        $categoryList = model('app\api\model\service\Category')
            ->where(['status'=>'normal','pid'=>0,'is_show'=>1])
            ->field('id,name')
            ->order('weigh desc')
            ->select();
        if($categoryList)
        {
            foreach ($categoryList as &$value)
            {
                $value['goodsList'] = \app\api\model\service\Goods::searchGoods(['category_id'=>$value['id'],'page'=>1,'limit'=>4,'city'=>$city]);
            }
        }
        $this->success('信息返回成功',$categoryList);
    }

    /**
     * 用户端项目详情
     * @return void
     */
    public function goodsInfo()
    {
        $uid = $this->auth->isLogin()?$this->auth->id:'';
        $id = input('id/d','');
        $seckill_id = input('seckill_id/d','');
        $uid = $this->auth->isLogin()?$this->auth->id:'';
        $info = \app\api\model\service\Goods::getInfo($id,$uid);
        !$info && $this->error('项目信息异常');
        $info['isPlus'] = $uid?\app\api\model\service\UserInfo::where('user_id',$uid)->value('is_plus'):0;
        if($seckill_id > 0){
            if($info['spec_type'] == 1){//多规格
                //echo $info['sku'][0]['price'];exit;
                $arr = [];
                $arr_rr = [];
                foreach ($info['sku'] as $k=>$v){

                    $p_data = Db::name("shopro_activity_goods_sku_price")->where(['sku_price_id'=>$v['id'],'activity_id'=>$seckill_id])->find();
                    //echo $p_data['price'];exit;
                    $arr['id'] = $v['id'];
                    $arr['name'] = $v['name'];
                    $arr['price'] = $p_data['price'];
                    $arr['sales'] = $p_data['sales'];
                    $arr['stock'] = $p_data['stock'];
                    $arr['salenums'] = $v['salenums'];
                    $arr_rr[] = $arr;

                }
                $info['sku'] = $arr_rr;
            }else{//单规格
                $shopro_activity_goods_sku_price = Db::name("shopro_activity_goods_sku_price")->where(['goods_id'=>$info['id'],'activity_id'=>$seckill_id])->find();
                $info['price'] = $shopro_activity_goods_sku_price['price'];
            }
        }
        $this->success('信息返回成功',$info);
    }

    /**
     * 服务人员更新服务项目
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function skillCategoryGoods()
    {
        $uid = $this->auth->id;
        $shop_id = \app\api\model\service\Skill::where(['user_id'=>$uid])->value('shop_id');
        $categoryList = \app\api\model\service\Category::where(['status'=>'normal','pid'=>0])->field('id,name')->select();
        $where['shop_id'] = $shop_id?['in',[0,$shop_id]]:0;
        $where['state'] = 1;
        foreach ($categoryList as &$value)
        {
            $where['category_id'] = $value['id'];
            $value['goodsList'] = \app\api\model\service\Goods::where($where)->field('id,name,image')->select();
        }
        $this->success('信息返回成功',$categoryList);
    }


    /**
     * 店铺添加项目
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function shopAddGoods()
    {
        $uid = $this->auth->id;
        $shop = \app\api\model\service\Shop::where(['user_id'=>$uid])->field('id,to_shop,province,city,district')->find();
        $post = input('post.','','trim,strip_tags');
        $post['shop_id'] = $shop['id'];
        $post['shop_user_id'] = $uid;
        $post['type'] = 1;
        $post['province'] = $shop['province'];
        $post['city'] = $shop['city'];
        $post['district'] = $shop['district'];
        (strstr($post['to_shop'],'shop') && $shop['to_shop'] == 0) && $this->error('未开通上门服务权限');
        $validate = Loader::validate('service.Goods');
        if(!$validate->scene('add')->check($post)){
            $this->error($validate->getError());
        }
        Db::startTrans();
        try{
            \app\api\model\service\Goods::addGoods($post);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('项目添加失败',$e->getMessage());
        }
        $this->success('项目已添加,等待管理员审核');
    }


    /**
     * 商户获得添加项目信息
     * @return void
     */
    public function shopGoodsInfo()
    {
        $id = input('id/d','');
        $goods = \app\api\model\service\Goods::getShopGoods($id);
        !$goods['id'] && $this->error('商品信息异常');
        $this->success('信息返回成功',$goods);
    }

    /**
     * 商户修改项目
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function shopEditGoods()
    {
        $uid = $this->auth->id;
        $id = input('id/d','');
        $shop = \app\api\model\service\Shop::where(['user_id'=>$uid])->field('id,to_shop')->find();
        $goodsId = \app\api\model\service\Goods::where(['id'=>$id,'shop_user_id'=>$uid])->value('id');
        !$goodsId && $this->error('商品信息异常');
        $post = input('post.','','trim,strip_tags');
        (strstr($post['to_shop'],'shop') && $shop['to_shop'] == 0) && $this->error('未开通上门服务权限');
        $validate = Loader::validate('service.Goods');
        if(!$validate->scene('edit')->check($post)){
            $this->error($validate->getError());
        }
        Db::startTrans();
        try{
            \app\api\model\service\Goods::editGoods($post);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('项目编辑失败',$e->getMessage());
        }
        $this->success('项目已编辑,等待管理员审核');
    }

    /**
     * 商户下架项目
     * @return void
     */
    public function downGoods()
    {
        $uid = $this->auth->id;
        $id = input('id/d','');
        $goodsId = \app\api\model\service\Goods::where(['id'=>$id,'shop_user_id'=>$uid,'status'=>'normal'])->value('id');
        !$goodsId && $this->error('当前商品无法下架');
        \app\api\model\service\Goods::downGoods($id);
        $this->success('商品已下架');
    }

    /**
     * 商户上架项目
     * @return void
     *
     */
    public function upGoods()
    {
        $uid = $this->auth->id;
        $id = input('id/d','');
        $goodsId = \app\api\model\service\Goods::where(['id'=>$id,'shop_user_id'=>$uid,'shop_state'=>1,'status'=>'hidden'])->value('id');
        !$goodsId && $this->error('当前商品无法上架');
        \app\api\model\service\Goods::upGoods($id);
        $this->success('商品已上架');
    }

    public function getUserGoods()
    {
        $uid = $this->auth->id;
        $type = input('type/d','');
        $userInfo = \app\api\model\service\UserInfo::where(['user_id'=>$uid])->field('id,user_id,is_skill,is_shop')->find();
        (($type == 0 && $userInfo['is_skill'] != 1) || ($type == 1 && $userInfo['is_shop'] != 1)) && $this->error('当前身份不符,无法查看');
        $goodsIds = $type == 0?\app\api\model\service\Skill::where(['user_id'=>$uid])->value('goods_ids'):\app\api\model\service\Shop::where(['user_id'=>$uid])->value('goods_ids');
        $goodsList = $type == 0?\app\api\model\service\Goods::getSkillGoods($goodsIds):\app\api\model\service\Goods::getShopPlatformGoods($goodsIds,$uid);

        $this->success('信息返回成功',$goodsList);
    }

    public function getApplyGoods()
    {
        $uid = $this->auth->id;
        $type = input('type/d','');
        $city = input('city','','trim,strip_tags');
        $category_id = input('category_id/d');
        $page = input('page/d','');
        $userInfo = \app\api\model\service\UserInfo::where(['user_id'=>$uid])->field('id,user_id,is_skill,is_shop')->find();
        $page = empty($page)?0:($page-1)*10;
        $limit = $page.',10';
        $config = config('database');
        $db = $config['prefix'].'service_goods';
        if(($type == 0 && $userInfo['is_skill'] == 0) || $type == 1)
        {
            $list = Db::query("SELECT id,name,shop_id,image,price,tag_name,response_hour,salenums,type,skill_cate_ids,category_id,city FROM {$db} WHERE (category_id={$category_id} AND status='normal' AND shop_id=0 AND shop_state=1) AND (city='{$city}' OR city IS NULL) AND (deletetime IS NULL) ORDER BY id DESC LIMIT {$limit}");
        }elseif($type == 0 && $userInfo['is_skill'] == 1)
        {
            $shop_id = \app\api\model\service\Skill::where(['user_id'=>$uid])->value('shop_id');
            if($shop_id){

                $list = Db::query("SELECT id,name,shop_id,image,price,tag_name,response_hour,salenums,type,skill_cate_ids,category_id,city FROM {$db} WHERE (category_id={$category_id} AND shop_state=1 AND status='normal' AND shop_id IN(0,'{$shop_id}')) AND (city='{$city}' OR city IS NULL) AND (deletetime IS NULL) ORDER BY id DESC LIMIT {$limit}");

            }else{

                $list = Db::query("SELECT id,name,shop_id,image,price,tag_name,response_hour,salenums,type,skill_cate_ids,category_id,city FROM {$db} WHERE (category_id={$category_id} AND shop_state=1 AND status='normal' AND shop_id=0) AND (city='{$city}' OR city IS NULL) AND (deletetime IS NULL) ORDER BY id DESC LIMIT {$limit}");
            }
        }
        $this->success('信息返回成功',$list);
    }



}
